package com.lynx.core.servlet;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.lynx.core.XmlPushMap;
import com.lynx.core.util.CONST;
import com.lynx.core.util.PackageClassUtil;
/**
 * 
 * @author lxp
 *
 */
public class FilterDispatcher implements Filter {

	
	
	public void destroy() {
		
	}

	public void doFilter(ServletRequest req, ServletResponse resp,FilterChain chain) throws IOException, ServletException {
		MyHttpRequest myRequest = new MyHttpRequest((HttpServletRequest) req);
		HttpServletResponse response = (HttpServletResponse)resp;
		String classPath = myRequest.getRequestURI();
		String keyUrl = classPath.substring(myRequest.getContextPath().length());
		String postfix = "";
		if(keyUrl.lastIndexOf(".")>-1){
			postfix = keyUrl.substring(keyUrl.lastIndexOf(".")+1);
			keyUrl = keyUrl.substring(0,keyUrl.lastIndexOf("."));
		}
		if (XmlPushMap.APIMAPS.containsKey(keyUrl)) {
			ViewRouter.processor(chain,myRequest, response, keyUrl,postfix);
		}else{
			chain.doFilter(myRequest,resp);
		}
			
	}

	public void init(FilterConfig cfg) throws ServletException {
		String path = cfg.getServletContext().getRealPath("");
		System.setProperty("WORKDIR", path);
		Enumeration<String> enumeration = cfg.getInitParameterNames();
		
		/**编码**/
		String EncodingStr = cfg.getInitParameter(CONST.Encoding);
		if(StringUtils.isNotBlank(EncodingStr)){
			CONST.EncodingVal=EncodingStr;
		}
		
		/**请求处理**/
		String webPath = cfg.getInitParameter(CONST.ApiServlet);
		if (webPath.startsWith("{")) {
			CONST.postfixStr = webPath.substring(webPath.indexOf("}->")).replaceAll("}->","");
			webPath = StringUtils.substringBetween(webPath, "{", "}");
		}
		String[] webs = webPath.split(",");
		PackageClassUtil packageClassUtil = new PackageClassUtil();
		XmlPushMap apiMap = new XmlPushMap();
		for (int i = 0; i < webs.length; i++) {
			String clsStr = webs[i];
			String postfix;
			if(clsStr.indexOf("->")>0){
				postfix = clsStr.substring(clsStr.indexOf("->")).replaceAll("->", ""); 
				clsStr = clsStr.substring(0,clsStr.indexOf("->"));
			}else{
				postfix = CONST.postfixStr;
			}
			Set<Class<?>> set = null;
			try {
				set = packageClassUtil.getClasses(clsStr);
			} catch (Exception e) {
				e.printStackTrace();
			}
			for (Class cls : set) {
				apiMap.SetMap(cls,postfix);
			}
		}
	}

}
